<template>
  <!-- 新增弹窗 -->
  <el-dialog
    v-model="medicineDialog"
    :title="drawerProps.title"
    width="1000"
    :before-close="handleClose"
  >
    <el-scrollbar height="400px" class="yDialog">
      <el-form
        ref="ruleFormRef"
        :model="drawerProps.row"
        :rules="rules"
        label-width="140px"
        :hide-required-asterisk="drawerProps.isView"
        :disabled="drawerProps.isView"
      >
        <el-form-item label="常数名" prop="name">
          <el-input
            v-model="drawerProps.row!.name"
            placeholder="请输入常数名..."
          />
        </el-form-item>
        <el-form-item label="所属常数类别" prop="family">
          <el-input
            v-model="drawerProps.row!.family"
            placeholder="请输入所属常数类别"
            disabled
          />
        </el-form-item>

        <!-- <el-form-item label="属性类型" prop="type">
          <el-input
            v-model="drawerProps.row!.type"
            placeholder="请输入属性类型"
            disabled
          />
        </el-form-item> -->
        <el-form-item label="所属系统" prop="system">
          <el-select
            v-model="drawerProps.row!.system"
            placeholder="请选择所属系统"
            size="samll"
            style="width: 240px"
            clearable
          >
            <el-option
              v-for="item in options"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关键字" prop="keyword">
          <el-input
            v-model="drawerProps.row!.keyword"
            placeholder="请输入关键字..."
          />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="drawerProps.row!.description"
            placeholder="请输入描述..."
          />
        </el-form-item>
        <el-form-item label="属性标准单位" prop="unit">
          <el-input
            v-model="drawerProps.row!.unit"
            placeholder="请输入属性标准单位..."
          />
        </el-form-item>
      </el-form>

      <el-collapse accordion class="human">
        <el-collapse-item title="人体属性区间" name="1">
          <el-scrollbar>
            <div class="cont">
              <!-- <div class="left"> -->

              <div
                class="one"
                v-for="(_item, index) in dataList.sectionForm"
                :key="index"
              >
                <el-form
                  :ref="(el) => (myFormRefs[index] = el)"
                  label-position="top"
                  :model="dataList.sectionForm[index]"
                  :rules="section"
                  label-width="140px"
                  :disabled="drawerProps.isView"
                >
                  <el-form-item label="稳态最小值" prop="min_value">
                    <el-input
                      v-model.number="dataList.sectionForm[index].min_value"
                      placeholder="请输入稳态最小值..."
                    />
                  </el-form-item>
                  <el-form-item label="平衡位置数据值" prop="balance_value">
                    <el-input
                      v-model.number="dataList.sectionForm[index].balance_value"
                      placeholder="请输入平衡位置数据值..."
                    />
                  </el-form-item>
                  <el-form-item label="稳态最大值" prop="max_value">
                    <el-input
                      v-model.number="dataList.sectionForm[index].max_value"
                      placeholder="请输入稳态最大值..."
                    />
                  </el-form-item>

                  <el-form-item label="指标单位描述" prop="description">
                    <el-input
                      v-model="dataList.sectionForm[index].description"
                      placeholder="请输入指标单位描述..."
                    />
                  </el-form-item>

                  <el-form-item label="性别" prop="gender">
                    <el-select
                      v-model.number="dataList.sectionForm[index].gender"
                      placeholder="请选择性别"
                      size="samll"
                      style="width: 240px"
                      clearable
                    >
                      <el-option key="item" label="男" :value="1" />

                      <el-option key="item" label="女" :value="2" />
                    </el-select>
                  </el-form-item>

                  <el-form-item label="指标单位" prop="unit_cover">
                    <el-input
                      v-model="dataList.sectionForm[index].unit_cover"
                      placeholder="请输入指标单位..."
                    />
                  </el-form-item>

                  <el-form-item label="开始年龄" prop="start_age">
                    <el-input
                      v-model.number="dataList.sectionForm[index].start_age"
                      placeholder="请输入开始年龄..."
                    />
                  </el-form-item>

                  <el-form-item label="结束年龄" prop="end_age">
                    <el-input
                      v-model.number="dataList.sectionForm[index].end_age"
                      placeholder="请输入结束年龄..."
                    />
                  </el-form-item>

                  <el-form-item label="偏移值" prop="offset">
                    <el-input
                      v-model.number="dataList.sectionForm[index].offset"
                      placeholder="请输入偏移值..."
                    />
                  </el-form-item>
                </el-form>
              </div>
              <!-- </div> -->
              <div class="right">
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="新增区间"
                  placement="bottom"
                  v-if="!drawerProps.isView"
                >
                  <el-icon size="20" style="cursor: pointer" @click="add">
                    <CirclePlusFilled />
                  </el-icon>
                </el-tooltip>

                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="删除区间"
                  placement="bottom"
                  :disabled="drawerProps.isView"
                  v-if="!drawerProps.isView"
                >
                  <el-icon
                    size="20"
                    color="#f32424"
                    style="cursor: pointer"
                    @click="remove"
                  >
                    <RemoveFilled />
                  </el-icon>
                </el-tooltip>
              </div>
            </div>
          </el-scrollbar>
        </el-collapse-item>
      </el-collapse>
    </el-scrollbar>

    <template #footer>
      <el-button @click="medicineDialog = false"> 取消 </el-button>
      <el-button
        v-show="!drawerProps.isView"
        type="primary"
        @click="handleSubmit"
      >
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="tsx" name="MedicineDialog">
import { ref, onMounted, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { getSystemListApi } from "@/api/modules";
const medicineDialog = ref(false);
let options = []; //医学所属系统列表
interface DrawerProps {
  title: string;
  isView: boolean;
  row: any;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const initRow = {
  family: "Y", //所属常数类别
  type: "医学", //属性类型
};
const handleClose = () => {
  medicineDialog.value = false;
};
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {},
});
const myFormRefs = ref([]);
const add = () => {
  dataList.sectionForm.push({});
  myFormRefs.value.push();
};
const remove = () => {
  dataList.sectionForm.pop();
  myFormRefs.value.pop();
  myFormRefs.value.slice(0, myFormRefs.value.length - 1);
  console.log(myFormRefs.value);
};

const section = reactive<any>({
  min_value: [
    { required: true, message: "请输入稳态最小值...", trigger: "blur" },
  ],
  balance_value: [
    { required: true, message: "请输入平衡位置数据值...", trigger: "blur" },
  ],
  max_value: [
    { required: true, message: "请输入稳态最大值...", trigger: "blur" },
  ],
  description: [
    { required: true, message: "请输入指标单位描述...", trigger: "blur" },
  ],
  gender: [{ required: true, message: "请选择性别...", trigger: "change" }],
});

const dataList = reactive({
  sectionForm: [],
});

onMounted(() => {
  getSystemList();
});

/**
 * @use 获取所属系统列表(医学)
 */
const getSystemList = async () => {
  try {
    const { data } = await getSystemListApi();
    options = data.system;
    console.log(options);
  } catch (error) {}
};

const rules = reactive<any>({
  name: [{ required: true, message: "请输入常数名...", trigger: "blur" }],
  keyword: [
    { required: true, message: "请输入关键词描述...", trigger: "blur" },
  ],
  description: [{ required: true, message: "请输入描述...", trigger: "blur" }],
  unit: [{ required: true, message: "请输入属性标准单位...", trigger: "blur" }],
  family: [{ required: true, trigger: "blur" }],
  type: [{ required: true, trigger: "blur" }],
  system: [{ required: true, message: "请选择所属系统", trigger: "change" }],
});
const ruleFormRef = ref<FormInstance>();
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

// 接收父组件传过来的参数
const acceptParams = (params: any) => {
  drawerProps.value = params;
  // drawerProps.value.row = { ...initRow };
  console.log(" drawerProps.value", drawerProps.value);

  resetForm(ruleFormRef.value);
  medicineDialog.value = true;
  if (params.title == "新增") {
    // 重置
    drawerProps.value.row = { ...initRow };
    dataList.sectionForm = [];
  } else if (params.title == "查看") {
    // Object.assign(dataList.sectionForm, drawerProps.value.row);
    // console.log(ruleForm);
    // resetForm(ruleFormRef.value)
    dataList.sectionForm = drawerProps.value.row.section;
  } else {
    dataList.sectionForm = JSON.parse(
      JSON.stringify(drawerProps.value.row.section)
    );
  }
};

const checkFrom = (formName: any) => {
  return new Promise((resolve, reject) => {
    formName.validate((valid: boolean) => {
      if (valid) {
        resolve(0);
      } else {
        reject();
      }
    });
  });
};

// 提交数据（新增/编辑）

const handleSubmit = () => {
  let dataItem = {
    min_value: null, //稳态最小值
    balance_value: null, //平衡位置数据值
    max_value: null, //稳态最大值
    description: "", //指标单位描述
    unit_cover: "", //指标单位
    gender: null, //性别
    start_age: null, //开始年龄
    end_age: null, //结束年龄
    offset: null, //偏移值
  };
  ruleFormRef.value!.validate(async (valid) => {
    if (!valid) return;
    try {
      let list = [];
      myFormRefs.value.map((item) => {
        if (item == null) return;
        list.push(checkFrom(item));
      });
      console.log("list", list);
      Promise.all(list).then(async () => {
        console.log("111");
        drawerProps.value.row.section = dataList.sectionForm.map((item) => {
          return {
            ...dataItem,
            ...item,
          };
        });
        console.log("整体数据", drawerProps.value.row);
        // const { data } = await addMedicineApi(ruleForm);
        // console.log("111", data);

        await drawerProps.value.api!(drawerProps.value.row);
        ElMessage.success({ message: `${drawerProps.value.title}成功！` });
        console.log(drawerProps.value);
        drawerProps.value.getTableList!();
        medicineDialog.value = false;
      });
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams,
});
</script>

<style scoped lang="scss">
@import "./yDialog.scss";
</style>
